<div style="text-align:center; margin:10px;"><h1>Workswap Board</h1></div>
<?php //WORKSWAP
	if(!strstr("xxx00001xxx00002jmf03007mcn02001mds00004",$_SESSION['netid'])) {
//	if(!strstr("jrb04008azc03001ebr05001jml05007jpm04006cps97001jmf03007cnf02001jpt02003mcn02001mds00004",$_SESSION['netid'])) {
		?>
		<div style="margin:20px; background-color:#FFFFCC; border: 1px solid #FFFF00; padding: 10px; text-align:center; font-weight: bold;">The workswap board is currently only available to testers. Please use the board at base until further notice.</div>
		<?php
		return;
	}

switch ($_REQUEST['workswap']) {
	case 'take':	
		//process rules
	
		//if they're an am, let them try to override..
		$manager_override = 0;
		if(checkQualified(1000) and isset($_REQUEST['man_override']))
			$manager_override = $_REQUEST['man_override'];
	
		if(isset($_REQUEST['driver_id']) and checkQualified(1000)) {
			//driver id is set by am to assign a shift to someone else
			$assigneeid = $_REQUEST['driver_id'];
			if (DEBUG) print "Setting driver to \$_REQUEST['driver_id'] = " . $_REQUEST['driver_id'];
		} else {
			//driver id is set by session variable
			$assigneeid = $_SESSION['driver_id'];
			if (DEBUG) print "Setting driver to session var = " . $_SESSION['driver_id'];
		}
		//
		
	
		//get table_id
		$grabTableID = mysql_query(sprintf("SELECT `t_sched_structure` . * FROM `t_workswap` , `t_sched_shifts` , `t_sched_structure` WHERE `t_workswap`.`shift_id` = `t_sched_shifts`.`shift_id` AND `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id` AND `t_workswap`.`workswap_id` = %s", quote_smart($_REQUEST['wsid'])));
		$structure_data = mysql_fetch_assoc($grabTableID);
		
		//get workswap data
		$grabWorkswap = mysql_query(sprintf("SELECT * FROM `t_workswap`,`t_sched_shifts` WHERE `t_workswap`.`workswap_id` = %s AND `t_workswap`.`shift_id` = `t_sched_shifts`.`shift_id`", quote_smart($_REQUEST['wsid'])));
		if(mysql_num_rows($grabWorkswap) != 1) {
			print "\n<div style='text-align: center;'>Invalid Workswap Shift (Error # S00)</div>";
			break;
		}
		$workswap_data = mysql_fetch_assoc($grabWorkswap);


	
		//determine if we should use the workswap start/end times or shift start/end times
		if($workswap_data['start'] == '') {
			//ok, no values in workswap, use shift start end times
			$wsStart = $workswap_data['shift_start'];
			$wsEnd   = $workswap_data['shift_end'];
			if(DEBUG) print "";
		} else {
			//ok, values exist, use workswap start end times
			$wsStart = $workswap_data['start'];
			$wsEnd   = $workswap_data['end'];
			if(DEBUG) print "";
		}
		
		if(ENFORCE_OVERLAP_WORKSWAP and !$manager_override) {     //*
			//check to see if this shift will overlap any other shift
			//is this a training shift??
			
			$row = $structure_data;
			if ($row['line'] == 'T') {
				//this is a training shift.. change the SQL code to remove training shifts.. TEMPORARY FIX!!
				$sql = sprintf("SELECT `t_sched_shifts`.* FROM `t_sched_shifts`,`t_sched_structure`
								WHERE `t_sched_shifts`.`driver_id` = %s 
								  AND `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id`
								  AND `t_sched_structure`.`line` <> 'T'
								  AND `t_sched_structure`.`table_id` = %s 
								  AND ( (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_end` < %s )
									 OR (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_start` < %s ) 
									 OR (`t_sched_shifts`.`shift_start` > %s AND `t_sched_shifts`.`shift_start` < %s )
									 )",
	
									quote_smart($assigneeid),
									quote_smart($structure_data['table_id']),
									quote_smart(subtractTime($wsStart,9)),
									quote_smart(addTime($wsEnd,9)),
									quote_smart(sprintf("%04d",$wsEnd)),
									quote_smart(sprintf("%04d",$wsStart)),
									quote_smart(sprintf("%04d",$wsStart)),
									quote_smart(sprintf("%04d",$wsEnd)));
			} elseif ( ($row['line'] == 'BW') or ($row['line'] == 'PM') ) {
				//it's not a training shift.. default SQL will do
				$sql = sprintf("SELECT `t_sched_shifts`.* FROM `t_sched_shifts`,`t_sched_structure`
								WHERE `t_sched_shifts`.`driver_id` = %s 
								  AND `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id`
								  AND `t_sched_structure`.`table_id` = %s 
								  AND ( (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_end` < %s )
									 OR (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_start` < %s ) 
									 OR (`t_sched_shifts`.`shift_start` > %s AND `t_sched_shifts`.`shift_start` < %s )
									 )",
	
									quote_smart($assigneeid),
									quote_smart($structure_data['table_id']),
									quote_smart($wsStart),
									quote_smart(addTime($wsEnd,9)),
									quote_smart(sprintf("%04d",$wsEnd)),
									quote_smart(sprintf("%04d",$wsStart)),
									quote_smart(sprintf("%04d",$wsStart)),
									quote_smart(sprintf("%04d",$wsEnd)));
			} else {
				//it's not a training shift.. default SQL will do
				$sql = sprintf("SELECT `t_sched_shifts`.* FROM `t_sched_shifts`,`t_sched_structure`
								WHERE `t_sched_shifts`.`driver_id` = %s 
								  AND `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id`
								  AND `t_sched_structure`.`table_id` = %s 
								  AND ( (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_end` < %s )
									 OR (`t_sched_shifts`.`shift_end` > %s AND `t_sched_shifts`.`shift_start` < %s ) 
									 OR (`t_sched_shifts`.`shift_start` > %s AND `t_sched_shifts`.`shift_start` < %s )
									 )",
	
									quote_smart($assigneeid),
									quote_smart($structure_data['table_id']),
									quote_smart(subtractTime($wsStart,9)),
									quote_smart(addTime($wsEnd,9)),
									quote_smart(sprintf("%04d",$wsEnd)),
									quote_smart(sprintf("%04d",$wsStart)),
									quote_smart(sprintf("%04d",$wsStart)),
									quote_smart(sprintf("%04d",$wsEnd)));
			}
			//this sql is long!!
			
			$overlap_result = mysql_query($sql);
			if(mysql_num_rows($overlap_result)) {
				$error .= "\n<div style='text-align: center;'>" . displayIcon(ICON_ERROR) . " Overlapping shift! (Error # S07)</div>";
			}
		}
	
		if(ENFORCE_PERMISSIONS and !$manager_override) {  //*
			//check permissions of the shift they are trying to take, and their permissions
			$sql = "SELECT `permission` FROM `t_drivers` WHERE `driver_id` = $assigneeid";
			if (DEBUG) print $sql;
			$perm_result = mysql_query($sql);
			$row_data = mysql_fetch_assoc($perm_result);
			$person_to_check = $row_data['permission'];
			if(!checkQualified($structure_data['permissions'],$person_to_check)) {
				$error .= "\n<div style='text-align: center;'>" . displayIcon(ICON_ERROR) . " You are not allowed to sign up for this shift! (Error # S08)</div>";
			}
			mysql_free_result($perm_result);
		}
		
		if(ENFORCE_40_HOUR_LIMIT_WORKSWAP and !$manager_override) {  //*
			//make sure they haven't gone over 40 hours
			
			//find out what week this shift is a part of
			$sql = sprintf("	SELECT `t_sched_main`.`week`,`t_sched_main`.`group_id` 
								FROM `t_sched_main`,`t_sched_structure`
								WHERE `t_sched_main`.`table_id` = `t_sched_structure`.`table_id`
								  AND `t_sched_structure`.`structure_id` = %s",
							$structure_data['structure_id']);
			$weekResult = mysql_query($sql);
			$weekRow = mysql_fetch_assoc($weekResult);
			$week = $weekRow['week'];
			$groupId = $weekRow['group_id'];
			mysql_free_result($weekResult);
			
			//Add up all shifts from this week
			$sql = sprintf("	SELECT `t_sched_shifts` . *
								FROM `t_sched_main` , `t_sched_structure` , `t_sched_shifts`
								WHERE `t_sched_main`.`week` = %s
								AND `t_sched_main`.`group_id` = %s
								AND `t_sched_main`.`table_id` = `t_sched_structure`.`table_id`
								AND `t_sched_structure`.`structure_id` = `t_sched_shifts`.`structure_id`
								AND `t_sched_shifts`.`driver_id` = %s",
							quote_smart($week),
							quote_smart($groupId),
							quote_smart($assigneeid));
			$allShiftsResult = mysql_query($sql);
			$hours = 0;
			if(mysql_num_rows($allShiftsResult) > 0) {
				while($row = mysql_fetch_assoc($allShiftsResult)) {
					$moreHours = paylogTime($row['shift_end']) - paylogTime(subtractTime($row['shift_start'],0010));
					$hours = $moreHours + $hours;
				}
			}
	
			//add in the current shift
			$moreHours = paylogTime($_REQUEST['endTime']) - paylogTime(subtractTime($_REQUEST['startTime'],0010));
			$hours = $moreHours + $hours;
			
			//check if it's over 40
			if($hours > 40) {
				$amountOver = $hours - 40;
				$error .= "\n<div style='text-align: center;'>" . displayIcon(ICON_ERROR) . " This shift would put you into overtime by " . $amountOver . "! (Error # S10)</div>";
			}
		}
	
		//verify that they are only a driver if they want to take buswash
		if(ENFORCE_BUSWASH_RESTRICTION_WORKSWAP and !$manager_override) {   //*
			$row = $structure_data;
			if ($row['line'] == 'BW') {
				//this is a bus wash shift.. check if they are too high up to take it
				$overQualified = false;
				if(checkQualified(0100) or checkQualified(0200) or checkQualified(0400))
					$overQualified = true;
				if($overQualified)
					$error .= "\n<div style='text-align: center;'>" . displayIcon(ICON_ERROR) . " You are overqualified for buswash. (Error # S12)</div>";
			}
		}
		
		//make sure the workswap wasn't taken..
		printDebug("DIDN'T CHECK IF SHIFT IS AVAILABLE.");

		//
		// Assuming all is good, assign the shift.. (ooh... so exciting!)
		//
	

		if(isset($error)) {
			// an error occurred
			print $error;
			print "<div style='text-align:center; font-size: 14px; font-weight: bold;'><a href='?workswap=view'>Return to Workswap</a></div>\n";
		} else {
			//take the shift..
			printDebug("I should take the shift!!");
			//data for this swap is in $workswap_data variable

			//check if this is an overridden perm shift... if so, create a new swap for it
			if(($_REQUEST['temp'] == 1) && empty($workswap_data['shift_date'])) {
				die("ERROR: Not updating temporary permanent swaps");
				//$sql = sprintf("INSERT INTO `t_workswap` ( `workswap_id` , `shift_id` , `orig_driver` , `new_driver` , `date_offered` , `date_taken` , `shift_date` , `redstar` , `start` , `end` , `comment` , `notify_email` , `notify_text` )
				//				VALUES (
				//					'0', '10', '0', NULL , '0', NULL , NULL , '0', NULL , NULL , '', '0', '0')",);
			}
			
			//update workswap table
			//permanent & temp swap
			$sql = sprintf("UPDATE `t_workswap` SET `date_taken` = %s, `new_driver` = %s WHERE `workswap_id` = %s LIMIT 1",date("Ymd"),quote_smart($assigneeid),$workswap_data['workswap_id']);
			printDebug("workswap update: $sql");
			$result = mysql_query($sql);
			//result is from update command... check if true

			if($result === true) {
				//permanent: - complete the workswap table, update the shift table;
				if(empty($workswap_data['shift_date'])) {
					//this is permanent... make the change on the schedule.
					$sql = sprintf("UPDATE `t_sched_shifts` SET `driver_id` = %s WHERE `shift_id` = %s LIMIT 1",quote_smart($assigneeid),$workswap_data['shift_id']);
					$result = mysql_query($sql);
					if($result === true) {
						printDebug("Shift swapped.");
					} else {
						die("Error updating shifts table. Workswap partially completed.");
					}
					printDebug("$sql");
				}
			} else {
				die("Couldn't update workswap table with new driver data.");
			}

			alertSuccess("You have been assigned this shift!");


			if($workswap_data['notify_email']) {
				printDebug("They wanted email notification... send it.");
				$email= '
				<div style="margin: 10px; text-align:center; font-size:16px; font-weight:bold; ">Congratulations!</div>
				<div style="margin: 10px; text-align:center; "><img src="http://transpo.uconn.edu/images/green-checkmark.png" height="88" width="100" alt="green-check"></div>
				<div style="margin: 10px; text-align:center; font-size:12px; ">Your workswapped shift was taken by ' . driverName($assigneeid) . '.</div>';
				sendEmail('matt.neilson@gmail.com','janet.freniere@uconn.edu','Good News: Workswapped shift taken!',$email);
			}

			if($workswap_data['notify_text']) {
				print "They wanted a text message.. Send it.";
				sendText($workswap_data['orig_driver'],"workswap text");
			}

		}
		break;

	case 'new':
?>			 <!-- Work Swap Module -->
<H2 align=center>Post Shift</H2>
<DIV style="MARGIN: 5px" align=center>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" name="newWorkswap">
<TABLE>
  <TR>
    <TH style="text-align:left; ">Your Name:</TH>

    <TD style="text-align:left; "><?php
		// ams  or d/ds
		if(checkQualified('1000') or checkDispatcher ()) {
			if(isset($_REQUEST['driverOverride'])) {
				?>
				<input type="hidden" name="override" value="<?= $_REQUEST['driverOverride'] ?>">
				<?php
				displayDriverSelect($_REQUEST['driverOverride'],true,"?workswap=new&amp;driverOverride=");
			} else {
				displayDriverSelect($_SESSION['driver_id'],true,"?workswap=new&amp;driverOverride=");
			} 
		} else {
			print driverName($_SESSION['driver_id']);
		}
		?></TD></TR>
<input type="hidden" name="workswap" value="post">

  <TR>
    <TH style="text-align:left; ">Your Shift:</TH>
	<td style="text-align:left; ">
	  <select id=shift name=shift onChange="resetPartialPrompt()">
	    <?php
		  $driver = $_SESSION['driver_id'];
		  if(isset($driverOverride)) $driver = $driverOverride;
		  $sql = 'SELECT `t_sched_shifts` . * , `t_sched_structure` . * , t_sched_main.`order` AS "main_order", t_sched_main.description AS "main_desc", t_sched_groups.description AS "group_desc", t_sched_groups.status, t_sched_groups.group_id
				FROM t_sched_shifts, t_sched_structure, t_sched_main, t_sched_groups
				WHERE t_sched_shifts.driver_id = ' . $driver . '
				AND t_sched_shifts.table_id = t_sched_main.table_id
				AND t_sched_main.group_id = t_sched_groups.group_id
				AND t_sched_groups.status > 0
				AND t_sched_shifts.structure_id = t_sched_structure.structure_id
				ORDER BY t_sched_groups.group_id DESC , t_sched_main.main_order ASC , t_sched_structure.`order` ASC
				';
		  $query = mysql_query($sql);
		  while($row = mysql_fetch_assoc($query)) {
		    if($row['group_desc'] != $last_group) {
				$last_group = $row['group_desc'];
				print "		<option disabled>" . $row['group_desc'] . "\n";
			}
			if($row['main_desc'] != $last_main) {
				$last_main = $row['main_desc'];
				print "		<option disabled>&nbsp;&nbsp;" . $row['main_desc'] . "\n";
			}
			print "		<option value='" . $row['shift_id'] . "'>&nbsp;&nbsp;&nbsp;&nbsp;" . $row['description'] . " " . $row['shift_start'] . " - " . $row['shift_end'] . "\n";
			
		  }
		?>
	  </select>
	</td>
  </TR>

  <TR>
    <TH style="text-align:left; ">Shift Date:</TH>
    <TD style="text-align:left; "><div id="shiftDate">Permanent  <input type="button" value="Pick Temp Date" onClick="displayShiftDates()"></div></TD>	
  </TR>
  <TR>
    <TH style="text-align:left; ">Duration of Shift:</TH>
	<td style="text-align:left; "><div id=shiftTimes>Entire Shift <input type="button" value="Workswap Part" onClick="displayTimepoints()"></div></td>
  </TR>
  <tr>
    <th style="text-align:left; ">Is this a RedStar?</th>
	<td style="text-align:left; "><input type=radio name=redStar value=1> Yes <input type=radio name=redStar value=0 checked> No</td>
  </tr>
  <tr>
    <th style="text-align:left; ">Comment:</th>
	<td style="text-align:left; "><input type=text name=comment></td>
  </TR>
  <tr>
    <td colspan=2 style="text-align:center; "><table style="margin:auto; " border="0" cellspacing="0" cellpadding="0">
      <tr>
        <th scope="row"><input type="checkbox" name="emailnotify" value="1" checked></th>
        <td style="text-align:left; "><?= displayIcon(ICON_EMAIL) ?> Notify me by email when this shift gets covered</td>
      </tr>
      <tr>
        <th scope="row"><input type="checkbox" name="txtnotify" id="txtnotify" onClick="alertTextWarning()" value="1"></th>
        <td style="text-align:left; "><?= displayIcon(ICON_PHONE) ?> Notify me by text message when this shift gets covered</td>
      </tr>
    </table>      </td>
  </tr>
  <tr>
    <td colspan=2 style="text-align:center; "><input name="submit" type="submit" value="Post to Workswap">
      <input name="reset" type=button onClick=reloadForm() value="Reset"></td>
  </tr>
</TABLE>
</form>
</DIV>				

<?php
       break;
   case 'post':
		//who's shift?
		$driver = $_SESSION['driver_id'];
		//but can they override??
		if(isset($_REQUEST['override']) && (checkQualified("1000") or checkDispatcher())) 
			$driver = $_REQUEST['override']; //guess so!
		
		//verify who is doing this (who's shift above) belongs to the shift
		if(isset($_REQUEST['shift'])) {
			//grab shift data
			$sql = sprintf("SELECT `driver_id` FROM `t_sched_shifts` WHERE `shift_id` = %s",
								quote_smart($_REQUEST['shift']));
			$result = mysql_query($sql);
			//make sure we got one, and only one result
			if(mysql_num_rows($result) != 1)
				die("Error grabbing shift data.");
			$data = mysql_fetch_assoc($result);
			//catch thrifty people who try to override shift but not driver!
			if($driver != $data['driver_id']) die("Shift/Driver mismatch.");
			mysql_free_result($result);
			$shift = $_REQUEST['shift'];
		} else {
			die("No shift data.");
		}
		
		
		//is this a temporary swap?
		if(isset($_REQUEST['tempDate'])) {
			$date = $_REQUEST['tempDate'];
			$dup_date = 'AND `shift_date` = ' . quote_smart($date);
		} else {
			$date = "NULL";
			$dup_date = 'AND `shift_date` IS NULL';
		}
		
		//is this a partial swap?
		if(isset($_REQUEST['start']) and isset($_REQUEST['end'])) {
			$start = $_REQUEST['start'];
			$end = $_REQUEST['end'];
			$dup_start = 'AND `start` = ' . quote_smart($_REQUEST['start']);
		} else {
			$start = "NULL";
			$end = "NULL";
			$dup_start = 'AND `start` IS NULL';
		}
		
		//redstar
		if(($_REQUEST['redStar'] == 0) or ($_REQUEST['redStar'] == 1)) {
			$redstar = $_REQUEST['redStar'];
		} else {
			printDebug("No/Invalid red star data.",LVL_ERROR);
		}
		
		//lets make sure this isn't a duplicate!!
		$sql = sprintf("SELECT * FROM `t_workswap` 
						WHERE `shift_id` = %s 
						  AND `orig_driver` = %s
						  %s
						  %s
						  AND `new_driver` IS NULL",  quote_smart($_REQUEST['shift']),quote_smart($driver),$dup_date,$dup_start);
		$result = mysql_query($sql);
		printMYSQLDebug($sql,$result);
		if($result === false) {
			//the query failed
			printMYSQLError($result);
			printDebug("The search query for duplicate swaps failed.",LVL_ERROR,"Query for duplicate ws check failed. " . $sql,1);
			return;
		} else {
			//the query succeeded
			if(mysql_num_rows($result) > 0) {
				//there is at least one result
				$data = mysql_fetch_assoc($result);
				printDebug("The shift you are trying to swap has already been posted to the workswap board.",LVL_ERROR,"Duplicate ws post: " . $data['workswap_id'],0);
				return;
			}
		}

		//notify by email
		if(isset($_REQUEST['emailnotify']) and ($_REQUEST['emailnotify'] == 1)) {
			$emailnotify = 1;
		} else {
			$emailnotify = 0;
		}
		
		//notify by text message
		if(isset($_REQUEST['txtnotify']) and ($_REQUEST['txtnotify'] == 1)) {
			$txtnotify = 1;
		} else {
			$txtnotify = 0;
		}
		
		//construct sql statement
		$sql = sprintf("INSERT INTO `t_workswap` (`workswap_id`,`shift_id`,`orig_driver`,`date_offered`,`shift_date`,`redstar`,`start`,`end`,`comment`,`notify_email`,`notify_text`) VALUES (0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
							quote_smart($shift),
							quote_smart($driver),
							date("Ymd"),
							quote_smart($date),
							quote_smart($redstar),
							quote_smart($start),
							quote_smart($end),
							quote_smart($_REQUEST['comment']),
							quote_smart($emailnotify),
							quote_smart($txtnotify));
		$result = mysql_query($sql);
		printMYSQLDebug($sql,$result);
		if($result === false) {
			printMYSQLError($result);
		} else {
			$rows = mysql_affected_rows();
			if($rows == 1) {
			?>
				<?= alertSuccess("You're shift has been posted!") ?>
				<?php
				if($emailnotify)
					print "<div style='text-align:center;'>You will be notified by email if this shift is taken.</div>\n";
				if($txtnotify)
					print "<div style='text-align:center;'>You will be notified by text message if this shift is taken.</div>\n";
				
				print "<div style='text-align:center; font-size: 14px; font-weight: bold;'><a href='?workswap=view'>Return to Workswap</a></div>\n";
			} else {
				printDebug("An error occurred posting your shift.",LVL_ERROR,"An error occurred trying to post the shift to the WS board.",1);
			}
		}
       break;
   case 'view':
?>			 <!-- Work Swap Module -->
			<script language="JavaScript" type="text/javascript">
				function confirmQuestion (continueURL,question) {
					if(confirm(question))
						document.location = continueURL;
				}
			</script>
<?php
		print "<div style='text-align:center;'><a href='" . $_SERVER['PHP_SELF'] . "?workswap=new'>Post Shift</a></div>\n";
		include("test-ws.php");
		break;
	case 'cancel':
		$result = mysql_query(sprintf("DELETE FROM `t_workswap` WHERE `workswap_id` = %s LIMIT 1", quote_smart($_REQUEST['wsid'])));
		if(mysql_affected_rows() == 1) {
			alertSuccess("Workswap Cancelled!");
		} else {
			if(mysql_affected_rows() == 0)
				errorText("Invalid Workswap Shift!");
			else
				errorText(mysql_errno() . ': ' . mysql_error());
		}
		?>
			<div style='text-align:center; font-size: 14px; font-weight: bold;'><a href='?workswap=view'>Return to Workswap</a></div>
		<?php
		break;
	default:
		break;
	}
 
 

?>